package com.dailyblue.java.project.power.controller;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.project.power.bean.JsonResult;
import com.dailyblue.java.project.power.bean.Users;
import com.dailyblue.java.project.power.service.UsersService;
import com.dailyblue.java.project.power.util.ResultCode;
import com.dailyblue.java.project.power.util.ResultTool;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/users")
public class UsersController {
    @Resource
    private UsersService usersService;

    @PostMapping(value = "/login", produces = {"application/json;charset=utf-8"})
    public String login(String userName, String password, HttpSession session) {
        System.out.println("login:" + userName + "\t" + password);
        return JSONArray.toJSONString(usersService.login(userName, password, session.getId(), session.getServletContext()));
    }

    @GetMapping("/logout")
    public void logout(String token, HttpSession session) {
        session.getServletContext().removeAttribute(token);
    }

    @GetMapping("/unique")
    public String uniqueName(String name) {
        return JSONArray.toJSONString(usersService.uniqueName(name));
    }

    @PostMapping("/save")
    public String save(Users user, HttpSession session) {
        return JSONArray.toJSONString(usersService.saveUser(user, session.getId(), session.getServletContext()));
    }

    @GetMapping("/a")
    public String a() {
        return "aaa";
    }

    @GetMapping("/update_role")
    public void updateRole(int rid, int uid) {
        usersService.updateUserByRole(rid, uid);
    }

    @GetMapping(value = "/update_power", produces = {"application/json;charset=utf-8"})
    public String updatePower(int uid, int[] pid) {
        return JSONArray.toJSONString(usersService.updateUserPower(uid, pid));
    }

    @GetMapping("/find")
    public String find() {
        return JSONArray.toJSONString(usersService.findAllUsers());
    }

    @GetMapping("/delete")
    public String delete() {
        return JSONArray.toJSONString(ResultTool.success(ResultCode.SUCCESS));
    }
}
